package com.zhou.system.management.security.authorization;


import com.zhou.common.lib.model.Response;
import com.zhou.common.lib.util.JSONUtils;
import com.zhou.system.management.constant.UserContext;
import com.zhou.system.management.security.model.MyUserDetails;
import com.zhou.system.management.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security 无权限处理 Handler
 * <p>
 * @serial 2.0.0
 * @author 就眠儀式
 */
@Slf4j
@Component
public class SecureAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        String requestURI = httpServletRequest.getRequestURI();
        MyUserDetails userDetails = UserContext.currentUser();
        log.info("{}暂无权限(url={})", userDetails.getUsername(), requestURI);
        if (ServletUtil.isAjax(httpServletRequest)) {
            ServletUtil.write(JSONUtils.toJson(Response.error(403, "暂无权限")));
        } else {
//            httpServletResponse.sendRedirect("/error/403");
            ServletUtil.write(JSONUtils.toJson(Response.error(403, "暂无权限")));
        }
    }
}
